/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;

/**
 *
 * @author Manuel
 */
public class DemoCertificados {

    public DemoCertificados() {
        /*try {
            demoHMACs();
        } catch (Exception ex) {
            Logger.getLogger(DemoCertificados.class.getName()).log(Level.SEVERE, null, ex);
        }*/
        //m();
        pruebaFirmas();
    }

    public static void main(String[] args) {
        DemoCertificados d = new DemoCertificados();
    }

    public void m() {
        try {
            java.security.KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
            String clave="compartir";
            String alias="Administrador";
            ks.load(new java.io.FileInputStream("c:/temp/Administrador.p12"), clave.toCharArray());
            Certificate certificado=ks.getCertificate("Administrador");
            PublicKey ja=certificado.getPublicKey();

        } catch (IOException ex) {
            Logger.getLogger(DemoCertificados.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(DemoCertificados.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(DemoCertificados.class.getName()).log(Level.SEVERE, null, ex);
        } catch (KeyStoreException ex) {
            Logger.getLogger(DemoCertificados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void demoHMACs() throws Exception {
        //   Obtener  el  MAC y escribirlo

        // Generar  llave secreta para  HMAC-MD5
        KeyGenerator kg = KeyGenerator.getInstance("HmacMD5");
        SecretKey sk = kg.generateKey();
        //Enviar la llave serializada
        //Servidor
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("c:/temp/llave.obj")));
        oos.writeObject(sk);
        oos.close();
        // Obtener instancia de objeto  Mac  e inicializar
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(sk);
        //Cliente recibe la llave
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("c:/temp/llave.obj")));
        SecretKey skCliente = (SecretKey) ois.readObject();

        byte[] mensaje = "Hola mundo".getBytes();
        byte[] elmac = mac.doFinal(mensaje);
        String s = new String(elmac);

        System.out.println("MAC serv: " + s);




        //  Verificar con el MAC
        Mac mac2 = Mac.getInstance("HmacMD5");
        mac2.init(skCliente);

        byte[] mensaje2 = "Hola mundo".getBytes();

        byte[] elmac2 = mac2.doFinal(mensaje2);
        String s2 = new String(elmac2);
        System.out.println("MAC clie: " + s2);

        boolean verifies2 = verificar(elmac, elmac2);
        System.out.println("Verificacion del MAC: " + verifies2);
        Mac mac3 = Mac.getInstance("HmacMD5");
        mac3.init(skCliente);
        byte[] mensaje3 = "Hola munda".getBytes();
        byte[] elmac3 = mac.doFinal(mensaje3);
        String s3 = new String(elmac3);
        System.out.println("MAC: " + s3);
        boolean verifies3 = verificar(elmac, elmac3);
        System.out.println("Verificacion del MAC: " + verifies3);
    }

    public static boolean verificar(byte[] dig1, byte[] dig2) {
        for (int i = 0; i < dig1.length - 1; i++) {
            if (dig1[i] != dig2[i]) {
                return false;
            }
        }
        return true;
    }

    public void pruebaFirmas() {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
            keyGen.initialize(512, new SecureRandom());
            KeyPair keyPair = keyGen.generateKeyPair();
            Signature signature = Signature.getInstance("SHA1withRSA", "BC");

            signature.initSign(keyPair.getPrivate(), new SecureRandom());

            //Mensaje a Firmar
            byte[] message = "ManolitoMariposaLinuz".getBytes();
            signature.update(message);

            byte[] sigBytes = signature.sign();
            System.out.println("tamaño firma: "+sigBytes.length);
            signature.initVerify(keyPair.getPublic());
            signature.update(message);
            System.out.println(signature.verify(sigBytes));
        } catch (Exception e) {
        }

    }
}
